package tools

import (
	"crypto/sha512"
	"errors"
	"fmt"
	"github.com/anaskhan96/go-password-encoder"
	"strings"
	"unicode"
)

func GeneratePwd(plaintext string) (ciphertext string, err error) {
	if len(strings.TrimSpace(plaintext)) == 0 {
		return "", errors.New("明文不能为空")
	}
	options := &password.Options{SaltLen: 16, Iterations: 100, KeyLen: 32, HashFunction: sha512.New}
	salt, encodedPwd := password.Encode(plaintext, options)
	ciphertext = fmt.Sprintf("$pbkdf2-sha512$%s$%s", salt, encodedPwd)
	return ciphertext, nil
}

func CheckPwd(oldPassword, checkPassword string) bool {
	//options := &password.Options{16, 100, 32, sha512.New}
	options := &password.Options{SaltLen: 16, Iterations: 100, KeyLen: 32, HashFunction: sha512.New}
	if !strings.Contains(oldPassword, "$") {
		return false
	}
	passwordInfo := strings.Split(oldPassword, "$")
	return password.Verify(checkPassword, passwordInfo[2], passwordInfo[3], options)
}

func CheckPasswordStrength(password string) (bool, error) {
	// 将密码字符串转换为 []rune 类型
	passwordRunes := []rune(password)

	// 密码长度至少6个字符
	if len(password) < 6 {
		return false, errors.New("密码长度至少6个字符")
	}
	// 检查密码中是否包含至少一个字母
	hasLetter := false
	for _, char := range passwordRunes {
		if unicode.IsLetter(char) {
			hasLetter = true
			break
		}
	}
	if !hasLetter {
		return false, errors.New("密码中需包含至少一个字母")
	}

	// 检查密码中是否包含至少一个数字
	hasDigit := false
	for _, ch := range passwordRunes {
		if unicode.IsDigit(ch) {
			hasDigit = true
			break
		}

	}
	if !hasDigit {
		return false, errors.New("密码中需包含至少一个数字")
	}

	//// 检查密码中是否包含至少一个特殊字符
	//hasSpecial:= false
	//for _,c :=range passwordRunes{
	//	if !unicode.IsDigit(c) && !unicode.IsLetter(c){
	//		hasSpecial = true
	//	}
	//}
	//if !hasSpecial{
	//	return false,errors.New("密码中需包含至少一个特殊字符")
	//}

	return true, nil
}
